/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.eventservice;

import im.eventpackage.Event;
import im.eventpackage.EventHandler;
import im.general.Config;
import im.messages.NotifyCHMessage;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author bluejack
 */
public class NotifyBehaviour extends OneShotBehaviour{

    //EventServiceAgent eventServiceAgent;
    EventHandler eventHandler;
    Event event;
    EventServiceAgent eventServiceAgent;
    
    public NotifyBehaviour(EventServiceAgent eventServiceAgent, Event event, EventHandler eventHandler) {
        this.eventServiceAgent = eventServiceAgent;
        this.eventHandler = eventHandler;
        this.event = event;
    }
    
    @Override
    public void action() {
        checkRecipients(event);
        notifyEventToCHs(event);
        try {
            Thread.sleep(40);
            //throw new UnsupportedOperationException("Not supported yet.");
        } catch (InterruptedException ex) {
            Logger.getLogger(NotifyBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    protected void notifyEventToCHs(Event event) {
        Set recipients = eventHandler.getRecipients(event);

        ACLMessage msg = new ACLMessage(ACLMessage.UNKNOWN);
        
        msg.setEncoding(Config.NOTIFY_NAME);
        try {
            msg.setContentObject(new NotifyCHMessage(event,(HashSet) recipients));
        } catch (IOException ex) {
            Logger.getLogger(NotifyBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        eventServiceAgent.addReceivers(eventServiceAgent.heads.keySet().iterator(), msg);

        if(recipients==null)
            return;

        eventServiceAgent.sendMessage(msg);
    }

    private void checkRecipients(Event event) {
        if(eventServiceAgent.eventHandler.getRecipients(event)==null)
            myAgent.removeBehaviour(this);
        if(eventServiceAgent.eventHandler.getRecipients(event).isEmpty()) {
            eventServiceAgent.eventHandler.removeEvent(event);
            myAgent.removeBehaviour(this);
        }

    }
}
